<template>
  <div>
    <a-timeline :pending="pending">
      <a-timeline-item v-for="(item, index) in mcpData" :key="index">
        <!-- 处理智能体分组 -->
        <div
          v-if="item.type === 'agent-group'"
          class="flex flex-col pb-2"
          :class="getCardAnimationClass(item.type)"
        >
          <AgentGroup
            :group="item.data"
            :animationClass="getCardAnimationClass(item.type)"
            :agentBgColor="agentBgColor"
            :agentColor="agentColor"
            :agentIcon="agentIcon"
          />
        </div>
        <!-- 处理路由器类型 -->
        <div v-else-if="item.type === 'router'" class="flex flex-col pb-2">
          <AgentRouter
            :router-data="item.data"
            :animationClass="getCardAnimationClass(item.type)"
            :agentBgColor="agentBgColor"
            :agentColor="agentColor"
            :agentIcon="agentIcon"
          />
        </div>
        <!-- 默认类型 -->
        <div class="flex flex-col pb-2" v-else>
          <AgentCard
            v-if="item.type === 'agent'"
            :agent="{ ...item.data, number: agentNumberMap.get(item.data.name) || 0 }"
            :execStep="0"
          />
          <ArtifactCard
            v-if="item.type === 'artifact'"
            :artifact="item.data"
            :onClick="handleShowReport"
          />
          <SummaryCard
            v-if="item.type === 'summary'"
            :summary="item.data?.summaryContent"
            :onClick="handleShowSummary"
          />
        </div>
      </a-timeline-item>
    </a-timeline>
    <a-modal v-model:visible="visible" width="90%">
      <div style="max-height: calc(90vh - 120px); overflow-y: auto">
        <img src="@/assets/images/合同图片.png" alt="" />
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref } from "vue";
import AgentGroup from "./agent-group.vue";
import AgentRouter from "./agent-router.vue";
import AgentCard from "./agent-card.vue";
import ArtifactCard from "./artifact-card.vue";
import SummaryCard from "./summary-card.vue";
import { data as rawData } from "./data.json";

const tempAgentNumberMap = {};

const agentNumberMap = ref(new Map());

const timelinePending = ref(true);

provide("timelinePending", timelinePending);

const pending = computed(() => {
  return timelinePending.value
    ? h(
        "span",
        {
          class: "text-indigo-700 text-sm",
        },
        "正在执行..."
      )
    : false;
});

const processData = computed(() => {
  const resultItems = [];
  let currentAgentNumber = 1;
  let currentGroup = null;
  const sortedItems = [...rawData].sort(
    (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
  );
  // 预先处理所有项，为智能体分配编号
  sortedItems.forEach((item) => {
    if (item.type === "agent" || item.type === "router") {
      const agentData = item.data;
      if (agentData && agentData.name) {
        // 如果这个智能体名称还没有分配编号，则分配一个新编号
        if (!tempAgentNumberMap[agentData.name]) {
          tempAgentNumberMap[agentData.name] = currentAgentNumber++;
        }
      }
    }
  });
  agentNumberMap.value = new Map(Object.entries(tempAgentNumberMap));

  // 处理每个时间线项目，只有相邻且同名的agent才合并
  sortedItems.forEach((item) => {
    // 如果不是agent类型，直接添加到结果列表
    if (!["agent", "router", "acp"].includes(item.type)) {
      resultItems.push(item);
      return;
    }

    // 获取agent数据
    const agentData = item.data;
    if (!agentData) return;

    // 如果是router类型，作为独立项目
    if (agentData.type === "router") {
      resultItems.push({
        ...item,
        type: "router",
      });
      return;
    }

    // 对于普通智能体或者ACP，检查是否能与当前分组合并
    const agentName = agentData.name;

    if (currentGroup && currentGroup.agentName === agentName) {
      // 相邻且同名，添加到当前分组
      currentGroup.steps.push(item);
    } else {
      // 不相邻或不同名，先添加当前分组到结果（如果存在），然后创建新分组
      if (currentGroup) {
        resultItems.push({
          id: currentGroup.id,
          type: "agent-group",
          timestamp: currentGroup.timestamp,
          data: currentGroup,
        });
      }

      // 创建新分组
      currentGroup = {
        id: item.id || crypto.randomUUID(),
        agentName,
        steps: [item],
        timestamp: item.timestamp,
      };
    }
  });
  // 处理最后一个分组
  if (currentGroup) {
    resultItems.push({
      id: currentGroup.id,
      type: "agent-group",
      timestamp: currentGroup.timestamp,
      data: currentGroup,
    });
  }
  // 按时间排序
  return resultItems.sort(
    (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
  );
});

const mcpData = ref([]);

const visible = ref(false);

const scrollToBottom = inject("scrollToBottom");

const loadding = (delay, start, end) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, delay);
  });
};

onMounted(async () => {
  mcpData.value = processData.value.slice(0, 1);
  timelinePending.value = true;
  scrollToBottom();
  await loadding(2000);
  timelinePending.value = false;
  mcpData.value = mcpData.value.concat(processData.value.slice(1, 4));
  timelinePending.value = true;
  scrollToBottom();
  await loadding(4000);
  timelinePending.value = false;
  mcpData.value = mcpData.value.concat(processData.value.slice(4, 9));
  timelinePending.value = true;
  scrollToBottom();
  await loadding(6000);
  timelinePending.value = false;
  mcpData.value = mcpData.value.concat(processData.value.slice(9));
  scrollToBottom();
});

provide("agentNumberMap", agentNumberMap);

const colorConfig = {
  primary: "#6366f1", // 默认蓝紫色
  secondary: "#e0e7ff", // 对应的浅色背景
  icon: "activity",
};
const agentColor = colorConfig.primary;
const agentBgColor = colorConfig.secondary;
const agentIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="10" rx="2"></rect><circle cx="12" cy="5" r="2"></circle><path d="M12 7v4"></path><line x1="8" y1="15" x2="8" y2="17"></line><line x1="16" y1="15" x2="16" y2="17"></line></svg>`;

// 获取卡片动画类名
const getCardAnimationClass = (type) => {
  // 初始加载时不应用动画效果
  if (!type) return "";
  if (type === "agent" || type === "agent-group") return "agentCardAnimation";
  if (type === "router") return "routerCardAnimation";
  if (type === "artifact") return "artifactCardAnimation";
  if (type === "summary") return "summaryCardAnimation";
  return "";
};

// 将十六进制颜色转换为RGB格式
function hexToRgb(hex) {
  // 移除可能的 # 前缀
  hex = hex.replace("#", "");

  // 解析十六进制值
  const r = parseInt(hex.substring(0, 2), 16);
  const g = parseInt(hex.substring(2, 4), 16);
  const b = parseInt(hex.substring(4, 6), 16);

  return `${r}, ${g}, ${b}`;
}

provide("hexToRgb", hexToRgb);

// 所有智能体使用统一的颜色
const AGENT_DOT_COLOR = "#6366f1"; // 主色调-蓝紫色
const ROUTER_DOT_COLOR = "#818cf8"; // 浅蓝紫色
const ARTIFACT_DOT_COLOR = "#a5b4fc"; // 淡蓝紫色
const SUMMARY_DOT_COLOR = "#4f46e5"; // 深蓝紫色

provide("AGENT_DOT_COLOR", AGENT_DOT_COLOR);
provide("ROUTER_DOT_COLOR", ROUTER_DOT_COLOR);
provide("ARTIFACT_DOT_COLOR", ARTIFACT_DOT_COLOR);
provide("SUMMARY_DOT_COLOR", SUMMARY_DOT_COLOR);
provide("colorConfig", colorConfig);

/**
 * 显示报告弹窗
 */
const handleShowReport = (artifact) => {
  visible.value = true;
};

const handleShowSummary = (data) => {
  visible.value = true;
};
</script>

<style>
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInLeft {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes fadeInRight {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes pulse {
  0% {
    opacity: 0;
    transform: scale(0.8);
    box-shadow: 0 0 0 0 rgba(59, 130, 246, 0);
  }
  50% {
    opacity: 0.9;
    transform: scale(1.05);
    box-shadow: 0 0 0 10px rgba(59, 130, 246, 0.2);
  }
  100% {
    opacity: 1;
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(59, 130, 246, 0);
  }
}

@keyframes highlight {
  0% {
    opacity: 0;
    transform: scale(0.9);
    box-shadow: 0 0 0 0 rgba(59, 130, 246, 0);
  }
  20% {
    opacity: 0.7;
    transform: scale(1.06);
    box-shadow: 0 0 10px 4px rgba(59, 130, 246, 0.4);
  }
  40% {
    opacity: 0.9;
    transform: scale(1.02);
    box-shadow: 0 0 5px 2px rgba(59, 130, 246, 0.3);
  }
  60% {
    opacity: 1;
    transform: scale(1.04);
    box-shadow: 0 0 8px 3px rgba(59, 130, 246, 0.35);
  }
  100% {
    opacity: 1;
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(59, 130, 246, 0);
  }
}

@keyframes highlightSummary {
  0% {
    opacity: 0;
    transform: scale(0.96);
    box-shadow: 0 0 0 0 rgba(139, 92, 246, 0);
  }
  20% {
    opacity: 0.7;
    transform: scale(1.01);
    box-shadow: 0 0 6px 2px rgba(139, 92, 246, 0.3);
  }
  40% {
    opacity: 0.9;
    transform: scale(1);
    box-shadow: 0 0 4px 1px rgba(139, 92, 246, 0.25);
  }
  60% {
    opacity: 1;
    transform: scale(1.005);
    box-shadow: 0 0 5px 2px rgba(139, 92, 246, 0.28);
  }
  100% {
    opacity: 1;
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(139, 92, 246, 0);
  }
}

/* ACP连接的动态网络动画 */
@keyframes acpPulse {
  0% {
    box-shadow: 0 0 0 0 rgba(129, 140, 248, 0.8), 0 0 0 0 rgba(129, 140, 248, 0.4);
    border-color: rgba(129, 140, 248, 0.8);
  }
  33% {
    box-shadow: 0 0 8px 3px rgba(129, 140, 248, 0.4), 0 0 12px 6px rgba(129, 140, 248, 0.1);
    border-color: rgba(79, 70, 229, 1);
  }
  66% {
    box-shadow: 0 0 4px 2px rgba(129, 140, 248, 0.6), 0 0 8px 4px rgba(129, 140, 248, 0.2);
    border-color: rgba(129, 140, 248, 0.6);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(129, 140, 248, 0.8), 0 0 0 0 rgba(129, 140, 248, 0.4);
    border-color: rgba(129, 140, 248, 0.8);
  }
}

/* ACP图标数据流动画 */
@keyframes dataFlow {
  0% {
    transform: translateX(-5px);
    opacity: 0.6;
  }
  50% {
    transform: translateX(5px);
    opacity: 1;
  }
  100% {
    transform: translateX(-5px);
    opacity: 0.6;
  }
}

/* 背景数据流动画 */
@keyframes backgroundFlow {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

/* ACP文字放大缩小动画 */
@keyframes acpTextPulse {
  0% {
    transform: scale(1);
    text-shadow: 0 0 0 rgba(79, 70, 229, 0);
  }
  50% {
    transform: scale(1.08);
    text-shadow: 0 0 4px rgba(79, 70, 229, 0.4);
  }
  100% {
    transform: scale(1);
    text-shadow: 0 0 0 rgba(79, 70, 229, 0);
  }
}

/* 时间线项目的动画 */
.timelineItemAnimation {
  animation: fadeInUp 0.5s ease-out forwards;
  min-height: unset !important;
}

/* 没有动画的时间线项目 */
.timelineItemNotAnimation {
  animation: none;
  min-height: unset !important;
}

/* 智能体卡片的动画 */
.agentCardAnimation {
  animation: fadeInLeft 0.5s ease-out forwards;
}

/* 路由器的动画 */
.routerCardAnimation {
  animation: fadeInRight 0.6s ease-out forwards;
}

/* 人工制品卡片的动画 */
.artifactCardAnimation {
  animation: highlight 1.2s ease-out forwards;
}

/* 汇总卡片的动画 */
.summaryCardAnimation {
  animation: highlightSummary 1.2s ease-out forwards;
}

/* ACP连接的动画组合 */
.acpPulseAnimation {
  animation: acpPulse 2s infinite ease-in-out;
  position: relative;
  transition: all 0.3s ease-in-out;
  z-index: 1;
}

/* 为ACP连接添加背景数据流动效果 */
.acpPulseAnimation::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    90deg,
    rgba(129, 140, 248, 0.1) 0%,
    rgba(99, 102, 241, 0.15) 25%,
    rgba(129, 140, 248, 0.2) 50%,
    rgba(99, 102, 241, 0.15) 75%,
    rgba(129, 140, 248, 0.1) 100%
  );
  background-size: 200% 100%;
  border-radius: inherit;
  z-index: -1;
  animation: backgroundFlow 3s infinite linear;
  pointer-events: none;
}

/* ACP连接图标的动画 */
.acpIconAnimation {
  animation: dataFlow 1.5s infinite ease-in-out;
}

/* ACP连接文字目标的动画 */
.acpTextAnimation {
  animation: acpTextPulse 1.8s infinite ease-in-out;
  display: inline-block;
  transform-origin: left center;
  font-weight: 500;
  letter-spacing: 0.01em;
}
</style>
